﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
using System.IO;
using Ionic.Zip;
using System.Xml;
using System.ComponentModel;
using System.Windows.Threading;

namespace RecommendedItemTool
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        ChampionSelect cs;
        public ItemSelect its;
        HelpScreen hs;        

        public string[] recommendedItems = { "", "", "", "", "", "" };
        List<string> championData = new List<string>();
        public Dictionary<string, ItemData> itemData = new Dictionary<string, ItemData>();

        public Dictionary<string, HeroData> heroData = new Dictionary<string, HeroData>();
        public string selectedChampion;

        Rectangle[] rPictureBoxes;

        public Rectangle draggingItemPic;
        string draggingItemID;

        public ItemToolTip itemToolTip;

        public AutoAbilityTool autoAbilityTool;
        public SetManager setManager;
        public AbilityManager abilityManager;
        public SavingOverlay savingOverlay;

        BackgroundWorker savingThread;
        DispatcherTimer draggingTimer;

        public bool isDraggingItem = false;
        public int draggingRecItem = -1;

        public Image backgroundImage;

        int currentSkinNum = 0;
        int skinCount = 0;        

        public MainWindow()
        {
            try
            {
                InitializeComponent();

                rPictureBoxes = new Rectangle[] { recItemImg1, recItemImg2, recItemImg3, recItemImg4, recItemImg5, recItemImg6 };
                //register the events for the item boxes
                for (int i = 0; i < rPictureBoxes.Length; i++)
                {
                    rPictureBoxes[i].Tag = i;
                    rPictureBoxes[i].MouseEnter += new MouseEventHandler(rPictureBoxes_MouseEnter);
                    rPictureBoxes[i].MouseLeave += new MouseEventHandler(rPictureBoxes_MouseLeave);
                    rPictureBoxes[i].MouseDown += new MouseButtonEventHandler(rPictureBoxes_MouseDown);
                }




                //  button1.Image = Bitmap.FromFile("button.png");

                //compile the list of items
                //use regex...just for the hell of it
                Dictionary<string, string> championNames = new Dictionary<string, string>();
                Regex r = new Regex(@"""(\w+)_(\w+)"" = ""([^""]+)");
                foreach (string s in File.ReadAllLines(LeagueUtils.FileFinder.fontConfigFinder()))
                {
                    Match m = r.Match(s);
                    if (m.Success)
                    {

                        string infoType = m.Groups[1].Value;
                        string infoID = m.Groups[2].Value;
                        string infoValue = m.Groups[3].Value;
                        if (infoType == "game_item_displayname")
                        {
                            itemData[infoID].name = infoValue;
                        }
                        else if (infoType == "game_character_lore" && infoValue.Length > 50
                            && File.Exists(LeagueUtils.FileFinder.findChampImageFolder() + "\\" + infoID + "_Square_0.png"))
                        {
                            heroData[infoID] = new HeroData(infoID, championNames[infoID]);
                        }
                        else if (infoType == "game_item_description")
                        {
                            itemData[infoID] = new ItemData(infoID);
                            itemData[infoID].description = infoValue;
                        }
                        else if (infoType == "game_character_displayname")
                            championNames[infoID] = infoValue;

                    }

                }

                foreach (string item in LeagueUtils.FileFinder.findInibinFiles())
                {

                    int zero = 0;
                    string d = item.Substring(item.LastIndexOf("\\") + 1);
                    string itemID = new String(d.ToCharArray(), 0, 4);
                    if (itemData.ContainsKey(itemID))
                    {
                        byte[] b = File.ReadAllBytes(item);
                        for (int i = 0; i < b.Length - 3; i++)
                        {
                            if (b[i] == 0)
                            {
                                zero = i;
                                continue;

                            }

                            if ((b[i] == ('d') && b[i + 1] == 'd' && b[i + 2] == 's') ||
                                (b[i] == 't' && b[i + 1] == 'g' && b[i + 2] == 'a') ||
                                (b[i] == 'D' && b[i + 1] == 'D' && b[i + 2] == 'S'))
                            {
                                itemData[itemID].iconFile = System.Text.ASCIIEncoding.ASCII.GetString(b, zero + 1, i - zero - 2) + ".png";

                                break;
                            }

                        }
                    }

                }

                //cache the hero icons
                foreach (KeyValuePair<string, HeroData> kvp in heroData)
                {

                    kvp.Value.icon = new BitmapImage(new Uri(LeagueUtils.FileFinder.findChampImageFolder() + "\\" + kvp.Key + "_Square_0.png"));
                }


                backgroundImage = new Image();
                backgroundImage.Width = Width;
                backgroundImage.Height = Height;
                Canvas.SetLeft(backgroundImage, 0);
                Canvas.SetTop(backgroundImage, -20);
                Canvas.SetZIndex(backgroundImage, -10);
                mainCanvas.Children.Add(backgroundImage);

                its = new ItemSelect(this);
                mainCanvas.Children.Add(its);
                Canvas.SetLeft(its, 20);
                Canvas.SetTop(its, 30);
                Canvas.SetZIndex(its, 0);
                its.Visibility = System.Windows.Visibility.Visible;

                //make Champion select and position, probably not pretty how i do it butttt its a start
                cs = new ChampionSelect(this);
                mainCanvas.Children.Add(cs);
                Canvas.SetLeft(cs, 0);
                Canvas.SetTop(cs, 0);
                Canvas.SetZIndex(cs, 20);
                cs.Visibility = System.Windows.Visibility.Hidden;



                //  hs.Show();
                hs = new HelpScreen(this);
                mainCanvas.Children.Add(hs);
                Canvas.SetZIndex(hs, 20);
                hs.Visibility = System.Windows.Visibility.Hidden;


                //init the item tooltip
                itemToolTip = new ItemToolTip();
                mainCanvas.Children.Add(itemToolTip);
                Canvas.SetZIndex(itemToolTip, 8);
                itemToolTip.Visibility = System.Windows.Visibility.Hidden;

                //init the dragging picturebox
                draggingItemPic = new Rectangle();
                draggingItemPic.Width = 50;
                draggingItemPic.Height = 50;
                draggingItemPic.RadiusX = 8;
                draggingItemPic.RadiusY = 8;
                draggingItemPic.Stroke = new SolidColorBrush(Colors.White);
                draggingItemPic.StrokeThickness = 2;
                draggingItemPic.Visibility = System.Windows.Visibility.Hidden;
                draggingItemPic.IsHitTestVisible = false;
                Canvas.SetZIndex(draggingItemPic, 9);
                mainCanvas.Children.Add(draggingItemPic);


                //autoAbilityTool
                autoAbilityTool = new AutoAbilityTool(this);
                Canvas.SetLeft(autoAbilityTool, 570);
                Canvas.SetTop(autoAbilityTool, 280);
                autoAbilityTool.Visibility = System.Windows.Visibility.Visible;
                Canvas.SetZIndex(autoAbilityTool, 1);
                mainCanvas.Children.Add(autoAbilityTool);

                //set manager
                setManager = new SetManager(this);
                Canvas.SetLeft(setManager,
                    Canvas.GetLeft(rPictureBoxes[0]) +
                    ((Canvas.GetLeft(rPictureBoxes[5]) + rPictureBoxes[5].Width - Canvas.GetLeft(rPictureBoxes[0])) -
                    setManager.Width) / 2);
                Canvas.SetTop(setManager, Canvas.GetTop(rPictureBoxes[0]) - setManager.Height - 2);
                setManager.Visibility = System.Windows.Visibility.Hidden;
                Canvas.SetZIndex(setManager, 2);
                mainCanvas.Children.Add(setManager);

                abilityManager = new AbilityManager(this);
                abilityManager.Visibility = Visibility.Hidden;
                Canvas.SetLeft(abilityManager, 600);
                Canvas.SetTop(abilityManager, 310);
                Canvas.SetZIndex(abilityManager, 1);
                mainCanvas.Children.Add(abilityManager);

                //saving overlay
                savingOverlay = new SavingOverlay();
                savingOverlay.Visibility = System.Windows.Visibility.Hidden;
                Canvas.SetZIndex(savingOverlay, 20);
                mainCanvas.Children.Add(savingOverlay);




                //background worker
                savingThread = new BackgroundWorker();
                savingThread.DoWork += new DoWorkEventHandler(savingThread_DoWork);
                savingThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(savingThread_RunWorkerCompleted);

                //dragging timer
                draggingTimer = new DispatcherTimer();
                draggingTimer.Interval = TimeSpan.FromMilliseconds(30);
                draggingTimer.Tick += new EventHandler(draggingTimer_Tick);

                selectChampion(this.heroData.ElementAt(0).Value.codeName);
            }
            catch (Exception e)
            {
                new LeagueOverlay.ScriptControl(null).log("[ERROR] (" + e.Source + "): " + e.Message + "\n" + e.StackTrace);
                throw;
            }
        }

        // If mouse is down, start dragging the selected item
        void rPictureBoxes_MouseDown(object sender, MouseButtonEventArgs e)
        {
            int id = (int)((Rectangle)sender).Tag;
            draggingRecItem = id;
            startDraggingItem(recommendedItems[id]);
        }

        // Empty
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }

        // Hide the tooltip when the mouse exits the frame
        void rPictureBoxes_MouseLeave(object sender, EventArgs e)
        {
            //hide the tooltip
            //toolTipLabel.Text = "";
            itemToolTip.Visibility = System.Windows.Visibility.Hidden;
            //(sender as Rectangle).Stroke = new SolidColorBrush(Colors.White);
        }

        // Show tooltip of the selected item (this is hidden if the current item is being dragged)
        void rPictureBoxes_MouseEnter(object sender, EventArgs e)
        {
            int boxNum = (int)(sender as Rectangle).Tag;
            string itemId = recommendedItems[boxNum];
            if (!itemData.ContainsKey(itemId)) return;

            itemToolTip.setItem(itemData[itemId]);
            Canvas.SetTop(itemToolTip, Canvas.GetTop((sender as Rectangle)) - itemToolTip.Height);
            Canvas.SetLeft(itemToolTip, Canvas.GetLeft((sender as Rectangle)) - itemToolTip.Width);

            itemToolTip.Visibility = System.Windows.Visibility.Visible;
            //(sender as Rectangle).Stroke = new SolidColorBrush(Colors.Orange);
        }

        public void selectChampion(string name)
        {
            try
            {
                string cName = name;
                selectedChampion = cName;
                autoAbilityTool.getAutoAbilityInfo();
                autoAbilityTool.initAbilityButtons();
                bool setManagerVisible = setManager.IsVisible;
                if (setManagerVisible) setManager.Visibility = Visibility.Hidden;

                // Get the champion data from the zip (stored in "DATA\\Characters\\" + cName + "\\" + cName + ".inibin")
                // extractChampionData(cName);
                string cFileName = "";
                foreach (string item in LeagueUtils.FileFinder.findInibinFiles())
                    if (item.Contains("\\" + cName + ".inibin"))
                    {
                        cFileName = item;
                        break;
                    }
                bool inXml = false;
                if (File.Exists("itemBuilds.xml"))
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load("itemBuilds.xml");
                    for (int i = 0; i < xmlDoc.DocumentElement.ChildNodes.Count; i++)
                    {
                        if (xmlDoc.DocumentElement.ChildNodes[i].Name == name)
                        {
                            inXml = true;
                            string[] items = xmlDoc.DocumentElement.ChildNodes[i].InnerText.Split('-');
                            for (int j = 0; j < 6; j++)
                            {
                                recommendedItems[j] = items[j];

                            }

                        }
                    }
                }

                if (File.Exists(cFileName) && inXml == false)
                {
                    FileStream fs = new FileStream(cFileName, FileMode.Open);
                    FileInfo fi = new FileInfo(cFileName);
                    byte[] cBytes = new byte[fi.Length];
                    int read = fs.Read(cBytes, 0, cBytes.Length);
                    fs.Close();
                    LeagueUtils.IniBinParser parser = new LeagueUtils.IniBinParser(cBytes);
                    int i = 0;
                    foreach (int item in parser.GetRecommendedItems())
                    {
                        recommendedItems[i] = item.ToString();
                        i++;
                    }

                }

                updateItemDisplay();
                skinCount = 1;

                while (File.Exists(LeagueUtils.FileFinder.findChampImageFolder() + "\\" + cName + "_Splash_" + skinCount + ".jpg"))
                    skinCount++;
                Random r = new Random();
                currentSkinNum = r.Next(0, skinCount);
                backgroundImage.Source =
                    new BitmapImage(
                        new Uri(LeagueUtils.FileFinder.findChampImageFolder() + "\\" + cName + "_Splash_" + currentSkinNum + ".jpg"));

                //mark the champion name
                championNameLbl.Content = heroData[cName].name;
                if (setManagerVisible) setManager.Visibility = System.Windows.Visibility.Visible;
            }
            catch (Exception e)
            {
                new LeagueOverlay.ScriptControl(null).log("[ERROR] (" + e.Source + "): " + e.Message + "\n" + e.StackTrace);
                throw;
            }
        }

        // Returns true if the string is a series of numbers
        public bool stringOnlyHasNumbers(string s)
        {
            for (int c = 0; c < s.Length; c++)
            {
                if (!Char.IsNumber(s, c)) return false;
            }
            return true;
        }

        // Inserts the recommended items into the rPictureBox for display
        public void updateItemDisplay()
        {
            for (int i = 0; i < 6; i++)
            {
                if (File.Exists(LeagueUtils.FileFinder.findItemIcons() + "\\" + itemData[recommendedItems[i]].iconFile))
                {
                    rPictureBoxes[i].Fill = new ImageBrush(new BitmapImage(new Uri(LeagueUtils.FileFinder.findItemIcons() + "\\" + itemData[recommendedItems[i]].iconFile)));
                }
                else
                {
                    rPictureBoxes[i].Fill = new ImageBrush(new BitmapImage(new Uri(Directory.GetCurrentDirectory() + "\\images\\image_not_found.png")));
                }               
            }
        }

        private void saveBtn_Click(object sender, EventArgs e)
        {
            savingOverlay.Visibility = Visibility.Visible;
            savingThread.RunWorkerAsync();
        }

        // Generates a string in the format <item1>-<item2>-<item3>-<item4>-<item5>-<item6>
        public string generateItemString()
        {
            string items = "";
            items += recommendedItems[0];
            for (int i = 1; i < 6; i++)
            {
                items += "-" + recommendedItems[i];
            }
            return items;
        }

        // Takes a string in the format <item1>-<item2>-<item3>-<item4>-<item5>-<item6>, changes each item to an int
        // And places that item code into the recommended item slot
        public bool loadItemString(string items)
        {
            items = items.Trim();
            string[] potentialItems = items.Split('-');

            if (potentialItems.Length == 6)
            {

                bool validItems = true;
                for (int i = 0; i < 6; i++)
                {
                    if (!itemData.ContainsKey(potentialItems[i]))
                    {
                        validItems = false;
                        break;
                    }
                }
                if (validItems)
                {
                    recommendedItems = potentialItems;
                    updateItemDisplay();
                    return true;
                }
            }
            return false;
        }

        // Item dragging handlers
        public void startDraggingItem(string ItemID)
        {
            draggingItemID = ItemID;
            if (File.Exists(LeagueUtils.FileFinder.findItemIcons() + "\\" + itemData[ItemID].iconFile))
            {
                draggingItemPic.Fill = new ImageBrush(new BitmapImage(
               new Uri(LeagueUtils.FileFinder.findItemIcons() + "\\" + itemData[ItemID].iconFile)));
            }
            else
            {
                draggingItemPic.Fill = new ImageBrush(new BitmapImage(new Uri(Directory.GetCurrentDirectory() + "\\images\\image_not_found.png")));
               
            }
          
            Point mouseLoc = Mouse.GetPosition(mainCanvas);
            Canvas.SetLeft(draggingItemPic, mouseLoc.X);
            Canvas.SetTop(draggingItemPic, mouseLoc.Y);
            draggingItemPic.Visibility = Visibility.Visible;
            draggingTimer.Start();
            isDraggingItem = true;
        }

        public void stopDraggingItem()
        {
            draggingTimer.Stop();
            draggingItemPic.Visibility = Visibility.Hidden;
            //check for drop over a box
            Point p = Mouse.GetPosition(mainCanvas);
            for (int i = 0; i < rPictureBoxes.Length; i++)
            {
                Rect picturePos = new Rect(
                    Canvas.GetLeft(rPictureBoxes[i]),
                    Canvas.GetTop(rPictureBoxes[i]),
                    rPictureBoxes[i].Width,
                    rPictureBoxes[i].Height);
                if (picturePos.Contains(p))
                {
                    if (draggingRecItem >= 0) recommendedItems[draggingRecItem] = recommendedItems[i];
                    recommendedItems[i] = draggingItemID;
                    
                    itemToolTip.setItem(itemData[recommendedItems[i]]);
                    Canvas.SetTop(itemToolTip, Canvas.GetTop(rPictureBoxes[i]) - itemToolTip.Height);
                    Canvas.SetLeft(itemToolTip, Canvas.GetLeft(rPictureBoxes[i]) - itemToolTip.Width);

                    updateItemDisplay();
                    break;
                }
            }
            isDraggingItem = false;
            draggingRecItem = -1;
        }

        private void draggingTimer_Tick(object sender, EventArgs e)
        {
            if (Mouse.LeftButton == MouseButtonState.Released)
            {
                stopDraggingItem();
            }
        }

        // Asynchronous thread for saving the current set of recommended items to the champion file
        private void savingThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            savingOverlay.Visibility = Visibility.Hidden;
            Canvas.SetZIndex(backgroundImage, -1);
        }

        private void savingThread_DoWork(object sender, DoWorkEventArgs e)
        {
            saveBuild(selectedChampion, generateItemString(), "", true);

            string cFileName = "";
            foreach (string item in LeagueUtils.FileFinder.findInibinFiles())
                if (item.Contains(selectedChampion + ".inibin"))
                    cFileName = item;

            if (File.Exists(cFileName))
            {
                LeagueUtils.FileRepair.BackupFile(cFileName);
                FileStream fs = new FileStream(cFileName, FileMode.Open);
                FileInfo fi = new FileInfo(cFileName);
                byte[] cBytes = new byte[fi.Length];
                int read = fs.Read(cBytes, 0, cBytes.Length);
                fs.Close();
                LeagueUtils.IniBinParser parser = new LeagueUtils.IniBinParser(cBytes);
                int[] beforeSave = parser.GetRecommendedItems();
                int[] newItems = {int.Parse(recommendedItems[0]),int.Parse(recommendedItems[1]),
                                     int.Parse(recommendedItems[2]),int.Parse(recommendedItems[3]),
                                     int.Parse(recommendedItems[4]),int.Parse(recommendedItems[5])};
                parser.SetRecommendedItems(newItems);
                int[] afterSave = parser.GetRecommendedItems();
                File.WriteAllBytes(cFileName, parser.returnByteArray());
            }
            else
            {
                //save failed...no message about this for now
                System.Diagnostics.Debug.WriteLine("saving failure..???");
                return;
            }
        }

        // Saves the current build to an xml file so it can be retrieved when the original file had been repaired
        // to it's original state.
        private void saveBuild(string champName, string itemBuild, string buildName, bool isDefault)
        {

            XmlDocument xmlDoc = new XmlDocument();
            if (File.Exists("itemBuilds.xml"))
            {
                xmlDoc.Load("itemBuilds.xml");
            }
            else
            {
                XmlElement elem = xmlDoc.CreateElement("Item_Builds");
                xmlDoc.AppendChild(elem);
                xmlDoc.Save("itemBuilds.xml");
            }

            bool hasName = false;
            XmlNodeList xmlList = (xmlDoc.DocumentElement.ChildNodes);
            for (int i = 0; i < xmlList.Count; i++)
            {
                if (xmlList[i].Name == champName)
                {
                    hasName = true;
                    break;
                }
            }

            if (hasName)
            {
                //when we're ready for multiple builds, you can check if this one is already defined and create a new one if needed
                xmlDoc.DocumentElement[champName]["Build" + 1].InnerText = itemBuild;
            }
            else
            {
                XmlElement champNode = xmlDoc.CreateElement(champName);
                xmlDoc.DocumentElement.AppendChild(champNode);
                XmlElement elem2 = xmlDoc.CreateElement("Build" + 1);
                elem2.InnerText = itemBuild;
                XmlAttribute att = xmlDoc.CreateAttribute("Build_Name");
                att.Value = buildName;
                XmlAttribute defAtt = xmlDoc.CreateAttribute("Default");
                defAtt.Value = isDefault == true ? "true" : "false";
                elem2.Attributes.Append(att);
                elem2.Attributes.Append(defAtt);

                xmlDoc.DocumentElement[champName].AppendChild(elem2);
            }

            xmlDoc.Save("itemBuilds.xml");

        }

        // Cleans up anything used during the recommended item process (not needed with the latest patcher)
        private void Window_Closed(object sender, EventArgs e)
        {
            //clean up if some files are left behind
            try
            {
                if (Directory.Exists("DATA")) Directory.Delete("DATA", true);
            }
            catch
            {
                //not much can be done
            }
        }

        // Brings the selected champion's canvas forward and hides the main canvas.
        private void championSelectBtn_Click(object sender, RoutedEventArgs e)
        {
            Canvas.SetZIndex(backgroundImage, 10);
            its.Visibility = Visibility.Hidden;
            cs.Visibility = Visibility.Visible;
        }

        // More item dragging handlers
        private void Window_MouseMove(object sender, MouseEventArgs e)
        {
            if (!isDraggingItem) return;
            Point p = e.GetPosition(mainCanvas);
            Canvas.SetLeft(draggingItemPic, p.X);
            Canvas.SetTop(draggingItemPic, p.Y);
        }

        private void mainCanvas_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (isDraggingItem) stopDraggingItem();
        }

        // Displays Help screen
        private void helpBtn_Click(object sender, RoutedEventArgs e)
        {
            Canvas.SetZIndex(backgroundImage, 10);
            its.Visibility = Visibility.Hidden ;
            hs.Visibility = Visibility.Visible;            
        }

        // Changes the background if user double clicks on the window
        private void Window_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            currentSkinNum = (currentSkinNum + 1) % skinCount;
            backgroundImage.Source =
                new BitmapImage(
                    new Uri(LeagueUtils.FileFinder.findChampImageFolder() + "\\" + selectedChampion + "_Splash_" + currentSkinNum + ".jpg"));
        }

        // Returns true if the ability is able to be levelled (based on its current value and the champion level)
        public bool[] levelableAbilities(int[] ab, int curLevel)
        {
            bool[] temp = new bool[4];

            //regular abilities
            for (int i = 0; i < 3; i++)
            {
                if (ab[i] * 2 + 1 <= curLevel)
                    temp[i] = true;
            }
            //ultimate
            if (curLevel == 16)
                temp[3] = true;
            else if (curLevel == 11)
                temp[3] = true;
            else if (curLevel > 11 && ab[3] < 2)
                temp[3] = true;
            else if (curLevel == 6)
                temp[3] = true;
            else if (curLevel > 6 && ab[3] < 1)
                temp[3] = true;

            return temp;
        }   

        private void mainCanvas_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.championSelectBtn.Focus();
        }

        // If key pressed is one of the ability keys, assume the user has clicked the button.
        private void mainCanvas_KeyUp(object sender, KeyEventArgs e)
        {
            //
            
            if (e.Key == Key.Q)
            {
                autoAbilityTool.Q_btn_Click(null, null);
            }
            else if (e.Key == Key.W)
            {
                autoAbilityTool.W_btn_Click(null, null);
            }
            else if (e.Key == Key.E)
            {
                autoAbilityTool.E_btn_Click(null, null);
            }
            else if (e.Key == Key.R)
            {
                autoAbilityTool.R_btn_Click(null, null);
            }
            
        }        

        // Loads an item string into the current champion
        private void loadViewItemStringBtn_Click(object sender, RoutedEventArgs e)
        {
            if (setManager.Visibility == Visibility.Hidden)
            {
                setManager.Visibility = Visibility.Visible;
            }
            else
            {
                setManager.Visibility = Visibility.Hidden;
            }
        }

        // Save the surrent build to the champion's file by running the saving thread.
        private void saveBtn_Click(object sender, RoutedEventArgs e)
        {
            Canvas.SetZIndex(backgroundImage, 10);
            savingOverlay.Visibility = Visibility.Visible;
            savingThread.RunWorkerAsync(); 
        } 
    }
}